package com.ddogring.web.controller.business;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ddogring.business.domain.Commodity;
import com.ddogring.business.domain.Order;
import com.ddogring.business.service.ICommodityService;
import com.ddogring.business.service.IOrderService;
import com.ddogring.common.constant.Constants;
import com.ddogring.common.core.controller.BaseController;
import com.ddogring.common.core.domain.AjaxResult;
import com.ddogring.common.core.domain.entity.SysUser;
import com.ddogring.common.core.redis.RedisCache;
import com.ddogring.common.utils.uuid.IdUtils;
import com.ddogring.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @BelongsProject: eshop
 * @BelongsPackage: com.ddogring.web.controller.business
 * @Author: DdogRing
 * @CreateTime: 2023-01-31  16:34
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * @description: 买家订单列表
     * @author: DdogRing
     * @date: 2023/1/31 16:42
     * @param: []
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/buyersList")
    public AjaxResult buyersList(@RequestBody Order order) {
        if (null == order || null == order.getAttributionId()) {
            order = new Order();
            order.setAttributionId(getLoginUser().getUserId().intValue());
            order.setStatus(2);
        }
        List<Order> orderList = orderService.selectBuyersList(order);
        return AjaxResult.success(orderList);
    }

    /**
     * @description: 卖家订单列表
     * @author: DdogRing
     * @date: 2023/1/31 16:43
     * @param: []
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/sellerList")
    public AjaxResult sellerList(@RequestBody Order order) {
        if (null == order) {
            order = new Order();
            SysUser sysUser = sysUserService.selectUserById(getLoginUser().getUserId());
            if (null != sysUser && null != sysUser.getShopUserId()) {
                order.setBusinessId(sysUser.getShopUserId().intValue());
            }
        } else if (null == order.getBusinessId()) {
            SysUser sysUser = sysUserService.selectUserById(getLoginUser().getUserId());
            if (null != sysUser && null != sysUser.getShopUserId()) {
                order.setBusinessId(sysUser.getShopUserId().intValue());
            }
        }

        if (null == order.pageNum()) {
            order.setPageNum(1);
        }
        if (null == order.pageSize()) {
            order.setPageSize(10);
        }

        Page<Order> page = new Page<>(order.pageNum(), order.pageSize());
        return getPage(orderService.selectSellerList(page, order), Order.class);
    }

    /**
     * @description: 生成订单
     * @author: DdogRing
     * @date: 2023/2/2 10:53
     * @param: [orders]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/save")
    public AjaxResult saveOrder(@RequestBody List<Order> orders) {

        if (null == orders || orders.size() == 0) {
            return AjaxResult.error("请求失败，请联系管理员");
        }

        Long userId = getLoginUser().getUserId();
        List<String> shopNames = new ArrayList<>();
        for (Order order:orders) {
            order.setOrderId(IdUtils.fastUUID());
            // 默认4待付款
            order.setStatus(4);
            order.setAttributionId(userId.intValue());
            orderService.save(order);

            // 更改商品库存
            int i = commodityService.updateRemainder(order.getShopId());
            if (i == 0) {
                Commodity commodity = commodityService.getById(order.getShopId());
                shopNames.add(commodity.getCommodity());
            }
        }

        // 修改购物车
        List<Commodity> cacheList = redisCache.getCacheList(Constants.SHOPPING_CART + userId);
        List<Commodity> tempList = new ArrayList<>(Arrays.asList(new Commodity[cacheList.size()]));
        Collections.copy(tempList, cacheList);
        for (Order order:orders) {
            Integer shopId = order.getShopId();
            for (Commodity commodity:cacheList) {
                if (commodity.getId().equals(shopId)) {
                    tempList.remove(commodity);
                }
            }
        }

        redisCache.deleteObject(Constants.SHOPPING_CART + userId);
        if (tempList.size() > 0) {
            redisCache.setCacheList(Constants.SHOPPING_CART + userId, tempList);
        }
        List<Order> orderList = orderService.selectOrderListByUserId(userId);
        AjaxResult success = AjaxResult.success(orderList);
        if (shopNames.size() > 0) {
            success.put("stock", shopNames);
        }
        return success;
    }

    /**
     * @description: 取消订单
     * @author: DdogRing
     * @date: 2023/2/8 12:46
     * @param: [order]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/cancel")
    public AjaxResult cancelOrder(@RequestBody Order order) {

        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>(order);
        // 取消订单
        updateWrapper.set("status", 5);
        return toAjax(orderService.update(updateWrapper));
    }
}
